/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package doc2db.interfaces.xmledit;

import doc2db.DbManager.DbSelects;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import doc2db.Keey;
import doc2db.fileWorker.FileBeginer;
import doc2db.fileWorker.FileWorker;
import java.awt.event.ActionListener;
import java.util.Properties;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
/**
 *
 * @author yuriy
 */
public class saveTemplatesInDBAction implements ActionListener {

    private String dbName;
    private String dbHost;
    private String dbUser;
    private String dbTableName;
    private final String port = "5432";

    private MTextArea text1;
    private MTextArea text2;
    private MTextArea textAbout;

    public saveTemplatesInDBAction(MTextArea t1, MTextArea t2, MTextArea ab){
        text1 = t1;
        text2 = t2;
        textAbout = ab;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int ret = JOptionPane.showConfirmDialog(null, "Создать шаблон ?",
                "Подтверждение", JOptionPane.YES_NO_OPTION);
        if (ret == JOptionPane.OK_OPTION) {
            if (!Keey.isConnected) {
                JOptionPane.showMessageDialog(null, "Соеденение не установленно",
                        "error", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String str = FileBeginer.resurse_resurseFolder + Keey.sp + FileBeginer.sqlSelects;
            String prop[][] = FileWorker.getProprtyList(str);
            if (!this.isAllProp(prop)) {
                JOptionPane.showMessageDialog(null, "Нет всех параметров базы\n" + str,
                        "error", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String pswd = JOptionPane.showInputDialog("Пароль БД с таблицами шабонов " +
                    "для пользователя "+ this.dbUser);
            if ((pswd != null) && (pswd.length() > 0)) {
            }else{
                return;
            }

            String name = JOptionPane.showInputDialog("Имя шаблона:");
            DbSelects db = this.getDbConnect(pswd);
            if (db == null) {
                JOptionPane.showMessageDialog(null, "Неудалось создать соеденение\n" + str,
                        "error", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String sTem = text1.getText().replace("\\", "\\\\").replace("\"", "\\\"").replace("\'", "\\\'");
            String sMTem = text2.getText().replace("\\", "\\\\").replace("\"", "\\\"").replace("\'", "\\\'");
            String sAb = textAbout.getText().replace("\\", "\\\\").replace("\"", "\\\"").replace("\'", "\\\'");
            db.sendQueryUpdate("CREATE TABLE " + dbTableName + " (" +
                    "\"id\" int2, \"name\" text, \"metaTemplates\" text, " +
                    "\"templates\" text, \"about\" text);");

            db.sendQuery(FileWorker.howInit(
                    FileBeginer.resurse_resurseFolder+Keey.sp+FileBeginer.sqlSelects,
                    "rowCount") + " " + dbTableName + ";");
            int idNow = db.getInt(1, 1);
            db.clear();

            boolean b = db.sendQueryUpdate("INSERT INTO " + dbTableName + " (" +
                    "\"id\", \"name\", \"metaTemplates\", \"templates\", \"about\")" +
                    " VALUES (" +
                    "\'"+idNow+"\', \'"+name+"\', \'"+sMTem+"\', \'"+sTem+"\', \'"+sAb+"');");
            
            if (b) {
                JOptionPane.showMessageDialog(null, "Данные внесены\n",
                        "ok", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "Неудалось внести данные\n" + str,
                        "error", JOptionPane.INFORMATION_MESSAGE);
            }

        }
    }

    private boolean isAllProp(String[][] str) {
        boolean tdbName = false;
        boolean tdbHost = false;
        boolean tdbUser = false;
        boolean tdbTableName = false;
        for (int i = 0; i < str.length; i++) {
            if (str[i][0].equals("templatesDbName")) {
                tdbName = true;
                this.dbName = str[i][1];
            }
            if (str[i][0].equals("templatesDbHost")) {
                tdbHost = true;
                this.dbHost = str[i][1];
            }
            if (str[i][0].equals("templatesDbUser")) {
                tdbUser = true;
                this.dbUser = str[i][1];
            }
            if (str[i][0].equals("templatesDbTableName")) {
                tdbTableName = true;
                this.dbTableName = str[i][1];
            }
        }

        return tdbName && tdbHost && tdbUser && tdbTableName;
    }

    private DbSelects getDbConnect(String pswd) {
        Properties props = new Properties();
        props.setProperty("user", dbUser);
        props.setProperty("password", pswd);
        StringBuffer url = new StringBuffer();
        url.append("jdbc:postgresql://").append(dbHost).append(":").
                append(port).append("/").append(dbName);

        DbSelects dBManager = null;
        try {
            dBManager = new DbSelects(url.toString(), props);
        } catch (SQLException ex) {
            return null;
        } catch (ClassNotFoundException ex) {
            return null;
        }
        if (! dBManager.isConnected()) {
            return null;
        }
        return dBManager;
    }
}